<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\UserGrowing;
use Illuminate\Support\Facades\DB;
class DeleteMoreUserGrowData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'delete:more_user_grow_data';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '删除user_grow重复数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $userGrows = DB::select("select user_id from users_growing  group by user_id having count(user_id)>=2");

        foreach($userGrows as $grow){

            $users = UserGrowing::where('user_id',$grow->user_id)->get();
            $fissionArr = [];
            $fissionSum = [];
            foreach($users  as $user){
                $this->writeLog($user);
                $fissionArr[$user->fission_id][0] = $user->fission_id;
                $fissionArr[$user->fission_id][1][] = $user->id;
                $fissionSum[$user->fission_id][] =1;
            }
//            print_r([$fissionArr,$fissionSum]);
            foreach($fissionArr as $k => $fission){
                if(count($fissionSum[$k]) >1){
                    array_shift($fission[1]);
                    UserGrowing::whereIn('id',$fission[1])->delete();
                }
            }
        }
        $this->info('修复完成');
    }

    public function writeLog($user){
//        dd(storage_path().'/logs/usergrowInfo.txt');
        $handle = fopen(storage_path().'/logs/usergrowInfo.txt','a');
        fwrite($handle,json_encode($user)."\n");
        fclose($handle);
    }
}
